package applet.logic;

import java.io.IOException;
import java.net.DatagramPacket;
import java.net.UnknownHostException;
import java.util.ArrayList;

import applet.connection.MediaReceiver;

public class MediaManager extends Thread{

	String _localAddress = null;
	int _localPort = 0;
	MediaReceiver _receiver = null;
	MediaReceiver _local = null;
	ArrayList <MediaReceiver> _forwarders = null;
	DatagramPacket _buffer = null;
	boolean _terminate = false;
	long cont = 0;
	
	
	public MediaManager(String address, int listenport, int playerport,int sendingport) {
		//super(address+ "Reader");
		_localAddress = address;
		_localPort = sendingport;
		_forwarders = new ArrayList<MediaReceiver>();
		try {
			_receiver = new MediaReceiver(null,0, _localAddress, listenport);
			_local = new MediaReceiver(_localAddress, playerport,_localAddress,_localPort);
		}  catch (UnknownHostException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
	}
	
	public void add_forward (String address, int port){
		try {
			get_forwarders().add(new MediaReceiver(address,port,_localAddress,_localPort));
		}  catch (UnknownHostException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
	}
	
	public void add_forward (MediaReceiver mm){
		get_forwarders().add(mm);
	}

	public void terminate() {
		_terminate = true;
		_receiver.close();
		_local.close();
		for (int i =0; i< get_forwarders().size(); i++){
			get_forwarders().get(i).close();
		}
	}

	public void run() {
		while (! _terminate){
			try {
				System.out.println("=========================================================================Reading: " + _receiver.get_socket().getLocalAddress().getAddress() + ":" + _receiver.get_socket().getLocalPort());
				_buffer = _receiver.read();
				if(_buffer != null){
					_local.write(_buffer);
					for (int i =0; i< get_forwarders().size(); i++){
						get_forwarders().get(i).write(_buffer);
					}
				}
			} catch (IOException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
			
			try {
				_buffer = _local.readRTCP();
				if(_buffer != null){
					_receiver.writeRTCP(_buffer);
				}
			} catch (IOException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
			
			try {
				for (int i =0; i< get_forwarders().size(); i++){
					_buffer = get_forwarders().get(i).readRTCP();
					if(_buffer != null){
						_receiver.writeRTCP(_buffer);
					}
				}
			} catch (IOException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
		}
	}
	
	public synchronized ArrayList<MediaReceiver> get_forwarders(){
		return _forwarders;
	}

}

